package com.yun.newBlog.blog.common;

import com.yun.newBlog.blog.vo.LoginSuccessResponseVo;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.social.connect.Connection;
import org.springframework.social.security.SocialAuthenticationToken;

public class LoginUtils {

    public static LoginSuccessResponseVo isLogin(){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        LoginSuccessResponseVo loginResponseVo = new LoginSuccessResponseVo();

        //有登陆用户就返回登录用户，没有就返回null
        if (authentication != null) {

            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                User user = (User) authentication.getPrincipal();
                loginResponseVo.setUsername(user.getUsername());
                loginResponseVo.setRole("admin");
            }

            if(authentication instanceof RememberMeAuthenticationToken){
                User user = (User) authentication.getPrincipal();
                loginResponseVo.setUsername(user.getUsername());
                loginResponseVo.setRole("admin");
            }

            if(authentication instanceof SocialAuthenticationToken){
                User user = (User) authentication.getPrincipal();
                loginResponseVo.setUsername(user.getUsername());

                Connection connection = ((SocialAuthenticationToken) authentication).getConnection();
                if(connection != null){
                    String imageUrl = connection.getImageUrl();
                    loginResponseVo.setImageUrl(imageUrl);
                    loginResponseVo.setRole("anonymousUser");
                }
            }
        }

        return loginResponseVo;
    }
}
